import qs from 'qs'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import axios from 'axios'
import jwt from "jwt-simple";
import router from '@/router';
import store from '@/store/index';
// 创建axios实例
export const service = axios.create({
    // baseURL: 'http://www.aidolphins.com:11000' + process.env.VUE_APP_BASE_API, // url = base url + request url
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    timeout: 30000,
    headers: []
})

function download (content, fileName) {
    const blob = new Blob([content]) //创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
    const url = window.URL.createObjectURL(blob)//URL.createObjectURL(object)表示生成一个File对象或Blob对象
    let dom = document.createElement('a')//设置一个隐藏的a标签，href为输出流，设置download
    dom.style.display = 'none'
    dom.href = url
    dom.setAttribute('download', fileName)//指示浏览器下载url,而不是导航到它；因此将提示用户将其保存为本地文件
    document.body.appendChild(dom)
    dom.click()
}

// request拦截器  前端给后端的请求
service.interceptors.request.use(
    config => {
        if (parseInt(storage.get("loginType")) === 0) {
            config.headers['tokens'] = "dabe69138599589384452ac32a0f43d6"
        } else {
            config.headers['tokens'] = storage.get("bmwToken") || "";
        }
        // 配置请求头
        config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/x-www-form-urlencoded' // 配置请求头
        config.headers['env'] = process.env.NODE_EN

        if (storage.get(ACCESS_TOKEN)) {
            config.headers['token'] = storage.get(ACCESS_TOKEN)
        }
        if (config.data === undefined) {
            // 写死了
            config.headers['YtAuth'] = jwt.encode({ "bmw": 1 }, "jwt")
        } else {
            // 过期时间
            config.data.exp = Math.floor(Date.now() / 1000) + 10;
            // 加密数据
            // config.headers['YtAuth'] = jwt.encode(config.data, "jwt")
            config.headers['YtAuth'] = jwt.encode({ "bmw": 1 }, "jwt")
        }

        // config.data = {"bmw":"你别整了,整不进去的,回家洗洗睡了吧!"}
        config.data = qs.stringify(config.data)

        return config
    },
    error => {
        // 请求错误
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// respone拦截器  后端给前端的响应
service.interceptors.response.use(
    response => {
        const res = response.data;
        if (response.status !== 200 || res.code !== 1) {
            if (res.errorMsg == "token过期" || res.errorMsg == '解密失败') {
                console.log(res.errorMsg);
                let loginType = JSON.parse(localStorage.getItem('loginType'))
                if (loginType == 0) {
                    router.push('/sign')
                    location.reload()
                } else if (loginType == 1) {
                    store.dispatch('Logout')
                }
                return
            }
            let lang = localStorage.getItem('lang')
            if (lang == '"zh-CN"') {
                return Promise.reject(res.showMsg)
            } else {
                return Promise.reject(res.showMsgEn)
            }
        } else {
            return res
        }
    },
    error => {
        let message = ''
        if (error.response) {
            const {
                status,
                data
            } = error.response
            switch (status) {
                case 400:
                    message = '400:错误的请求'
                    break
                case 403:
                    message = '403:服务器拒绝了对所请求资源的访问'
                    break
                case 404:
                    message = '404:网络请求不存在'
                    break
                case 500:
                    message = '500:服务器断开连接，请稍后再试'
                    break
                case 502:
                    message = '502:服务器没有响应，请稍后再试'
                    break
                case 503:
                    message = '503:因维护而停机，无法处理请求'
                    break
                default:
                    message = `Error:${data.showMsg}`
            }
        } else {
            if (error.message.includes('timeout')) {
                message = `Error:请求超时! 请检查网络是否正常`
            } else {
                message = `Error:请求失败，请检查网络是否已连接`
            }
        }
        return Promise.reject({
            message
        })
    }
)


export function post (url, data, headers) {
    // console.log(data);
    return service({
        method: 'post',
        url: url,
        data: data,
        headers: headers || {}
    })
}
export function blob (url, data, headers) {
    return service({
        method: 'post',
        url: url,
        data: data,
        responseType: "blob",
        headers: headers || {}
    })
}
export function get (url, params, headers) {
    return service({
        method: 'get',
        url,
        params: params,
        headers: headers || {}
    })
}

export function formData (url, data) {
    return service({
        method: 'POST',
        url,
        data,
        headers: { 'Content-Type': 'multipart/form-data' }
    })
}
/* 下载更新  */
export const downloposts = (url, data, config = {}) => {
    return new Promise((resolve, reject) => {
        service({
            method: 'post',
            url: url,
            data,
            responseType: 'blob',//服务器返回的数据类型
            headers: { 'Content-Type': 'multipart/form-data' }
        })
            .then((response) => {
                const content = response.data //返回的内容
                const fileName = "12" //文件名
                console.log(response)
                return
                download(content, base.decode(fileName))
            })
            .catch((error) => {
                reject(error)
            })
    })
}